#include "app_router.h"
#include "app_mqtt.h"
#include "log/log.h"
#include "app_message.h"

#define MAX_DEVICE_NUM 10

static Device *device_list[MAX_DEVICE_NUM] = {0};

int app_router_init(void)
{
    return app_mqtt_init();
}

int app_router_registerDevice(Device *dev)
{
    size_t i;
    for (i = 0; i < MAX_DEVICE_NUM; i++)
    {
        // 找到重复或者没有注册的空位置，注册设备
        if (device_list[i] == dev)
        {
            log_warn("Device %s has been registered", dev->name);
            return -1;
        }
        else if (device_list[i] == NULL)
        {
            device_list[i] = dev;
            log_debug("Device %s has been registered", dev->name);
            app_device_start(dev);
            return 0;
        }
    }
    // 没有位置了
    log_error("Device list is full");
    return -1;
}

int app_router_devToMqtt(Device *dev, void *data, size_t len)
{
    // router拿到二进制数据，转化为json字符串，发布到MQTT服务器
    char json_str[1024];
    Message *msg = app_message_initFromBinary(data, len);
    if (!msg)
    {
        log_error("Invalid message %s", data);
        return -1;
    }

    if (msg->type != dev->type)
    {
        log_error("Device type mismatch %d %d", msg->type, dev->type);
        goto DEVICE_FAIL_TO_SEND;
    }

    int ret_len = app_message_saveAsJson(msg, json_str, sizeof(json_str));
    if (ret_len < 0)
    {
        log_error("Failed to save message %s to json", data);
        goto DEVICE_FAIL_TO_SEND;
    }

    if (app_mqtt_publish(json_str, ret_len) < 0)
    {
        log_error("Failed to publish message %s to mqtt", json_str);
        goto DEVICE_FAIL_TO_SEND;
    }
    app_message_free(msg);
    return 0;

DEVICE_FAIL_TO_SEND:
    app_message_free(msg);
    return -1;
}

int app_router_mqttToDev(void *data, size_t len)
{
    // 1. 找到消息对应的设备
    unsigned char buf[1024];
    Message *msg = app_message_initFromJson(data, len);
    if (!msg)
    {
        log_error("Invalid message %s", data);
        return -1;
    }

    for (size_t i = 0; i < MAX_DEVICE_NUM; i++)
    {
        if (!device_list[i])
        {
            goto NO_SUITABLE_DEVICE;
        }
        if (device_list[i]->type == msg->type)
        {
            // 2. 将消息写入设备
            int len = app_message_saveAsBinary(msg, buf, 1024);
            if (len < 0)
            {
                log_warn("Failed to save message %s", data);
                goto FAIL_TO_SEND;
            }

            if (app_device_write(device_list[i], buf, len) < 0)
            {
                log_warn("Failed to write message %s to device", data);
                goto FAIL_TO_SEND;
            }
            // 3. 释放消息
            app_message_free(msg);
            return 0;
        }
    }

NO_SUITABLE_DEVICE:
    // 没有找到设备
    log_warn("No suitable device for message %s", data);
FAIL_TO_SEND:
    app_message_free(msg);
    return -1;
}

void app_router_deinit(void)
{
    // 释放设备列表
    for (size_t i = 0; i < MAX_DEVICE_NUM; i++)
    {
        if (!device_list[i])
        {
            break;
        }
        app_device_stop(device_list[i]);
        app_device_deinit(device_list[i]);
    }

    // 关闭MQTT
    app_mqtt_deinit();
}
